﻿using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using PlugNT.Safe;
using PlugNT.Common;

namespace PlugNT.Custom
{
    /// <summary>
    /// Web配置类
    /// </summary>
    public class WebConfig
    {
        private static string _configpath = null;  //配置文件路径
        private static string _rootpath = null;
        private static string _dbname;
        private static string _dbtype;
        private static string _connectionstring;
        private static string _admininterfacekey;
        private static string _sitename;
        private static string _siteurl;
        private static string _waterimagepath;
        private static string _logoimagepath;
        private static string _uploadpath;
        private static string _tableprefix;
        private static string _tablepostfix;
        private static string _filepathlist;

        private static string _userstablename;
        private static string _usersidname;
        private static string _usersusername;
        private static string _userspassname;
        private static string _usersencryptway;
        private static string _usersencryptinterface;
        private static string _usersselectfields;
        private static string _userslockeds;

        private static string _indexpath;
        private static bool _isautoupdate;
        private static string _autodatespan;
        private static bool _commentlocked = true; //评论
        private static int _memorysize = 30;     //指定内存大小
        private static bool _isaccess = false;

        //不可更新字段
        private static string _sessionadminer;
        private static string _sessionuser;
        private static string _sessioncode;

        //支付宝
        private static string _alipaykey;
        private static string _alipayselleremail;
        private static string _alipaypartner;
        private static string _alipaytype;



        private const string _version = "2.0";  //版本
        private const string configfilename = "Site.config";

        internal static string alipaysecurity = "alipay";   //支付宝密匙
        static WebConfig()
        {

            try
            {
                InitConfigs();
            }
            catch (Exception ex)
            {
                SysManager.LogErrorWriteln(ex.Message + "\n" + ex.StackTrace);
            }
        }

        //当前程序版本
        public static string Version
        {
            get
            {
                return _version;
            }
        }

        /// <summary>
        /// 根目录
        /// </summary>
        public static string RootPath
        {
            get
            {
                if (_rootpath == null)
                {
                    _rootpath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
                    //System.Configuration.ConfigurationSettings.AppSettings["RootPath"];
                    if (!System.IO.Directory.Exists(_rootpath))
                    {
                        throw new Exception("根目录路径未设置正确！");
                    }
                }
                return _rootpath;
            }
        }


        /// <summary>
        /// 配置文件文件夹
        /// </summary>
        public static string ConfigPath
        {
            get
            {
                if (_configpath == null)
                {
                    _configpath = RootPath + "Config\\";
                }
                return _configpath;
            }
        }


        /// <summary>
        /// 返回数据库名称
        /// </summary>
        public static string DbName
        {
            get
            {
                return _dbname;
            }
        }

        /// <summary>
        /// 返回MySql.Data.MySqlClient，System.Data.SqlClient，System.Data.OleDb，System.Data.Odbc，System.Data.OracleClient
        /// </summary>
        public static string DbType
        {
            get
            {
                return _dbtype;
            }
        }

        /// <summary>
        /// 连接字符串
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                return _connectionstring;
            }
        }

        /// <summary>
        /// 后台接口密码
        /// </summary>
        public static string AdminInterfaceKey
        {
            get
            {
                return _admininterfacekey;
            }
        }

        /// <summary>
        /// 网站名称
        /// </summary>
        public static string SiteName
        {
            get
            {
                return _sitename;
            }
        }

        /// <summary>
        /// 网站地址
        /// </summary>
        public static string SiteUrl
        {
            get
            {
                return _siteurl;
            }
        }

        /// <summary>
        /// 网站地址
        /// </summary>
        public static string WaterImagePath
        {
            get
            {
                return _waterimagepath;
            }
        }

        /// <summary>
        /// 网站地址
        /// </summary>
        public static string LogoImagePath
        {
            get
            {
                return _logoimagepath;
            }
        }

        /// <summary>
        /// 文件上传路径
        /// </summary>
        public static string UploadPath
        {
            get
            {
                return _uploadpath;
            }
        }

        /// <summary>
        /// Cms表名前缀
        /// </summary>
        public static string TablePrefix
        {
            get
            {
                return _tableprefix;
            }
        }

        /// <summary>
        /// Cms表名后缀
        /// </summary>
        public static string TablePostfix
        {
            get
            {
                return _tablepostfix;
            }
        }


        /// <summary>
        /// 站点文件路径
        /// </summary>
        public static string FilePathList
        {
            get
            {
                return _filepathlist;
            }
        }

        /// <summary>
        /// SessionAdminer
        /// </summary>
        public static string SessionAdminer
        {
            get
            {
                return _sessionadminer;
            }
        }

        /// <summary>
        /// SessionUser
        /// </summary>
        public static string SessionUser
        {
            get
            {
                return _sessionuser;
            }
        }

        /// <summary>
        /// SessionCode
        /// </summary>
        public static string SessionCode
        {
            get
            {
                return _sessioncode;
            }
        }



        /// <summary>
        /// 用户表名
        /// </summary>
        public static string UsersTableName
        {
            get
            {
                return _userstablename;
            }
        }
        /// <summary>
        /// 编号字段名
        /// </summary>
        public static string UsersIdName
        {
            get
            {
                return _usersidname;
            }
        }
        /// <summary>
        /// 用户字段名
        /// </summary>
        public static string UsersUserName
        {
            get
            {
                return _usersusername;
            }
        }
        /// <summary>
        /// 密码字段名
        /// </summary>
        public static string UsersPassName
        {
            get
            {
                return _userspassname;
            }
        }
        /// <summary>
        /// 密码加密类型(0为标准MD5加密，1为自定义加密，2为其他方式加密)
        /// </summary>
        public static string UsersEncryptWay
        {
            get
            {
                return _usersencryptway;
            }
        }
        /// <summary>
        /// 密码加密接口(url?pass=)
        /// </summary>
        public static string UsersEncryptInterface
        {
            get
            {
                return _usersencryptinterface;
            }
        }
        /// <summary>
        /// 后台查看字段(field->fieldtitle->titlewidth,field->fieldtitle,field)
        /// </summary>
        public static string UsersSelectFields
        {
            get
            {
                return _usersselectfields;
            }
        }
        /// <summary>
        /// 锁定用户名
        /// </summary>
        public static string UsersLockeds
        {
            get
            {
                return _userslockeds;
            }
        }



        /// <summary>
        /// 生成首页文件的路径
        /// </summary>
        public static string IndexPath
        {
            get { return _indexpath; }
        }

        /// <summary>
        /// 是否评论
        /// </summary>
        public static bool CommentLocked
        {
            get { return _commentlocked; }
        }

        /// <summary>
        /// 内存大小
        /// </summary>
        public static int MemorySize
        {
            get { return _memorysize; }
        }

        /// <summary>
        /// 是否是Access数据库
        /// </summary>
        public static bool IsAccess
        {
            get
            {
                return _isaccess;
            }
        }

        /// <summary>
        /// 是否自动更新页面
        /// </summary>
        public static bool IsAutoUpdate
        {
            get { return _isautoupdate; }
        }

        /// <summary>
        /// 自动更新页面间隔
        /// </summary>
        public static string AutoDateSpan
        {
            get { return _autodatespan; }
        }

        //支付宝信息
        public static string AlipayKey
        {
            get { return _alipaykey; }
        }
        public static string AlipaySelleremail
        {
            get { return _alipayselleremail; }
        }
        public static string AlipayPartner
        {
            get { return _alipaypartner; }
        }
        public static string AlipayType
        {
            get { return _alipaytype; }
        }



        /// <summary>
        /// 动态页模板
        /// </summary>
        public static Dictionary<string, string> AspxTemplets = null;

        /// <summary>
        /// SQL语句关键字
        /// </summary>
        public static Dictionary<string, string> SqlKeyValues = null;


        /// <summary>
        /// 根据字符串获取属性值
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetPropertyValue(string name)
        {
            try
            {
                return typeof(PlugNT.Custom.WebConfig).GetProperty(name, BindingFlags.Public | BindingFlags.Static).GetValue(null, null).ToString();
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 得到动态页模板路径
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetAspxTempletPath(string url)
        {
            return AspxTemplets[url].Split('|')[0];
        }

        /// <summary>
        /// 得到动态页模板路径(无参数)
        /// </summary>
        /// <returns></returns>
        public static string GetAspxTempletPath()
        {
            return AspxTemplets[System.Web.HttpContext.Current.Request.RawUrl.ToLower().Split('?')[0]].Split('|')[0];
        }


        /// <summary>
        /// 初始化配置信息
        /// </summary>
        private static void InitConfigs()
        {

            XmlDocument xml = new XmlDocument();
            xml.Load(ConfigPath + configfilename);

            //XmlNode node = xml.SelectSingleNode("/bookstore/book[@name='aaa']");    //选择一个
            //XmlNodeList nodes = xml.SelectNodes("/bookstore/book[@name='aaa']");    //选择多个

            InitConfig(xml);

            InitAlipay(xml);

            InitAutoUpdate(xml);

            xml = null;


        }

        internal static void InitConfig(XmlDocument xml)
        {
            if (xml == null)
            {
                xml = new XmlDocument();
                xml.Load(ConfigPath + configfilename);
            }
            //初始化dbinfo
            _dbname = xml.SelectSingleNode("/configs/db/dbname").InnerXml.Trim();
            _dbtype = xml.SelectSingleNode("/configs/db/dbtype").InnerXml.Trim();    //DESEncrypter.Decrypt(_dbtype);
            _connectionstring = xml.SelectSingleNode("/configs/db/connectionstring").InnerXml.Trim();

            _admininterfacekey = xml.SelectSingleNode("/configs/admininterfacekey").InnerXml.Trim();
            _sitename = xml.SelectSingleNode("/configs/sitename").InnerXml.Trim();
            _siteurl = xml.SelectSingleNode("/configs/siteurl").InnerXml.Trim();
            _waterimagepath = xml.SelectSingleNode("/configs/waterimagepath").InnerXml.Trim();
            _logoimagepath = xml.SelectSingleNode("/configs/logoimagepath").InnerXml.Trim();
            _uploadpath = xml.SelectSingleNode("/configs/uploadpath").InnerXml.Trim();
            _tableprefix = xml.SelectSingleNode("/configs/db/tableprefix").InnerXml.Trim();
            _tablepostfix = xml.SelectSingleNode("/configs/db/tablepostfix").InnerXml.Trim();
            _filepathlist = xml.SelectSingleNode("/configs/filepathlist").InnerXml.Trim();

            _sessionadminer = xml.SelectSingleNode("/configs/sessionadminer").InnerXml.Trim();
            _sessionuser = xml.SelectSingleNode("/configs/sessionuser").InnerXml.Trim();
            _sessioncode = xml.SelectSingleNode("/configs/sessioncode").InnerXml.Trim();

            _userstablename = xml.SelectSingleNode("/configs/users/tablename").InnerXml.Trim();
            _usersidname = xml.SelectSingleNode("/configs/users/idname").InnerXml.Trim();
            _usersusername = xml.SelectSingleNode("/configs/users/username").InnerXml.Trim();
            _userspassname = xml.SelectSingleNode("/configs/users/passname").InnerXml.Trim();
            _usersencryptway = xml.SelectSingleNode("/configs/users/encryptway").InnerXml.Trim();
            _usersencryptinterface = xml.SelectSingleNode("/configs/users/encryptinterface").InnerXml.Trim();
            _usersselectfields = xml.SelectSingleNode("/configs/users/selectfields").InnerXml.Trim();
            _userslockeds = xml.SelectSingleNode("/configs/users/lockeds").InnerXml.Trim();

            _indexpath = xml.SelectSingleNode("/configs/indexpath").InnerXml.Trim();
            _connectionstring = _connectionstring.Replace("%RootPath%", _rootpath);


            XmlNode aspxs = xml.SelectSingleNode("/configs/templet/aspx");
            AspxTemplets = new Dictionary<string, string>();
            if (aspxs.ChildNodes.Count > 0)
            {
                foreach (XmlNode n in aspxs.ChildNodes)
                {
                    if (n.NodeType != XmlNodeType.Comment && n.Name.ToLower() == "item")
                    {
                        XmlAttribute key = n.Attributes["name"];
                        if (key != null)
                        {
                            AspxTemplets.Add(key.Value.ToLower(), n.InnerXml);
                        }
                    }
                }
            }

            XmlNode sqlkeyvalues = xml.SelectSingleNode("/configs/db/sql");
            SqlKeyValues = new Dictionary<string, string>();
            if (sqlkeyvalues.ChildNodes.Count > 0)
            {

                foreach (XmlNode n in sqlkeyvalues.ChildNodes)
                {
                    if (n.NodeType != XmlNodeType.Comment && n.Name.ToLower() == "item")
                    {
                        XmlAttribute key = n.Attributes["name"];
                        if (key != null)
                        {
                            SqlKeyValues.Add(key.Value.ToLower(), n.InnerXml);
                        }
                    }
                }
            }

            //是否access数据库
            _isaccess = (_dbtype == "System.Data.OleDb");
            //是否锁定评论
            _commentlocked = xml.SelectSingleNode("/configs/commentlocked").InnerText.Trim().ToLower() == "false" ? false : true;
            //内存大小
            _memorysize = int.Parse(xml.SelectSingleNode("/configs/memorysize").InnerText.Trim());
            //支付宝密匙
            alipaysecurity = _sessionadminer + _sessionuser + _sessioncode;
        }

        internal static void InitAlipay(XmlDocument xml)
        {
            if (xml == null)
            {
                xml = new XmlDocument();
                xml.Load(ConfigPath + configfilename);
            }

            _alipayselleremail = Encrypter.DESDecrypt(xml.SelectSingleNode("/configs/alipay/selleremail").InnerXml.Trim(), alipaysecurity);
            _alipaykey = Encrypter.DESDecrypt(xml.SelectSingleNode("/configs/alipay/key").InnerXml.Trim(), alipaysecurity);
            _alipaypartner = Encrypter.DESDecrypt(xml.SelectSingleNode("/configs/alipay/partner").InnerXml.Trim(), alipaysecurity);
            _alipaytype = Encrypter.DESDecrypt(xml.SelectSingleNode("/configs/alipay/type").InnerXml.Trim(), alipaysecurity);

        }

        internal static void InitAutoUpdate(XmlDocument xml)
        {
            if (xml == null)
            {
                xml = new XmlDocument();
                xml.Load(ConfigPath + configfilename);
            }
            //自动更新
            _isautoupdate = xml.SelectSingleNode("/configs/templet/autoupdate/locked").InnerText.Trim().ToLower() == "false" ? false : true;
            _autodatespan = xml.SelectSingleNode("/configs/templet/autoupdate/datespan").InnerText.Trim();
        }


        /// <summary>
        /// 配置文件字符串
        /// </summary>
        /// <returns></returns>
        public static string GetConfigString()
        {

            return @"<?xml version=""1.0"" encoding=""utf-8""?>
            <configs>
              <!-- 网站名称 -->
              <sitename>$sitename$</sitename>
              <!-- 网站地址 -->
              <!--<siteurl>http://www.plugnet.cn</siteurl>-->
              <siteurl>$siteurl$</siteurl>
              <!-- 水印图片-->
              <waterimagepath>$waterimagepath$</waterimagepath>
              <!--logo图片-->
              <logoimagepath>$logoimagepath$</logoimagepath>
              <!-- 数据库配置信息（只能在该文件中修改） -->
              <db>
                <!--
                <dbtype>System.Data.SqlClient</dbtype>
                <connectionstring>Data Source=127.0.0.1;User ID=sa;Password=123123;Initial Catalog=PlugNT.ase;Pooling=true</connectionstring>
                //-->
                <!-- SELECT id FROM `order` limit 1 //-->
                <!--
                <dbtype>MySql.Data.MySqlClient</dbtype>
                <connectionstring>Server=localhost;Database=zuitu_db;Uid=root;Pwd=123123;charset=utf8</connectionstring>
                //-->
                <!--
                <dbtype>System.Data.OleDb</dbtype>
                <connectionstring>Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%RootPath%\App_Data\site.mdb;User ID=;Password=;</connectionstring>
                //-->
                <dbname>$dbname$</dbname>
                <dbtype>$dbtype$</dbtype>
                <connectionstring>$connectionstring$</connectionstring>
                <!--cms表名前缀 -->
                <tableprefix>$tableprefix$</tableprefix>
                <!--cms表后缀名-->
                <tablepostfix>$tablepostfix$</tablepostfix>
                <!--SQL语句<item name=""testsql""></item>-->
                <sql></sql>
              </db>
              <!-- 后台接口密码 -->
              <admininterfacekey>888888</admininterfacekey>
              <!-- 文件上传路径 -->
              <uploadpath>$uploadpath$</uploadpath>
              <!-- 站点根目录文件夹路径(只能在该文件夹中修改文件) -->
              <filepathlist>$filepathlist$</filepathlist>
              <!--生成首页文件的路径 -->
              <indexpath>$indexpath$</indexpath>
              <!-- SessionAdminer -->
              <sessionadminer>$sessionadminer$</sessionadminer>
              <!-- SessionUser -->
              <sessionuser>$sessionuser$</sessionuser>
              <!-- SessionCode -->
              <sessioncode>$sessioncode$</sessioncode>
              <users>
                <!-- 用户表名 -->
                <tablename></tablename>    
                <!-- 编号字段名 -->
                <idname>id</idname>
                <!-- 用户字段名 -->    
                <username>username</username>
                <!-- 密码字段名 -->    
                <passname>password</passname>
                <!-- 密码加密类型(0为标准MD5加密，1为自定义加密，2为其他方式加密) -->    
                <encryptway>0</encryptway>
                <!-- 密码加密接口(url?pass=) -->    
                <encryptinterface></encryptinterface>
                <!-- 后台查看字段(field,field,field)*表示全部 -->    
                <selectfields></selectfields>
                <!-- 锁定用户名(每个用户名后必须以,结尾) -->
                <lockeds></lockeds>
              </users>
              <!-- cms模板 -->
              <templet>
                <!--locked-网页自动更新，datespan-0为不启用，1-7为星期一到星期天，timespan为时间间隔-->
                <autoupdate>
                  <locked>$autoupdatelocked$</locked>
                  <datespan>$autoupdatedatespan$</datespan>
                </autoupdate>
                <!--动态模板-->
                <aspx>
                  <item name=""文章列表"">/articles.aspx|true</item>
                  <item name=""评论页"">/comment.aspx</item>
                </aspx>
              </templet>
              <!--支付宝selleremail为帐号,key为校验码,partner为合作者身份ID(通过加密的数据)type为支付宝接口类型-->
              <alipay>
                <selleremail>$alipayselleremail$</selleremail>
                <key>$alipaykey$</key>
                <partner>$alipaypartner$</partner>
                <type>$alipaytype$</type>
              </alipay>
              <!--内存大小-->
              <memorysize>30</memorysize>
              <!--评论审核-->
              <commentlocked>$commentlocked$</commentlocked>
            </configs>";
        }



    }

}

